
//: @"bubble_right_1" 
Byte kClimbStarfruitPolarBear[] = {
    93, 14, 30, 4, 128, 147, 128, 128, 138, 131, 125, 144, 135, 133, 134, 146, 125, 79, 117
};

//: @"bubble_left_1" 
Byte kMacawIceApplePlunge[] = {
    174, 13, 47, 4, 145, 164, 145, 145, 155, 148, 142, 155, 148, 149, 163, 142, 96, 101
};

//
//  GTLMessageBaseCell.m
//  ChatDemo
//
//  Created by 九月 on 1/1/25.
//

#import "GTLMessageBaseCell.h"

#import "WQUMessageCell.h"

@interface GTLMessageBaseCell ()

@property (nonatomic, strong) UITapGestureRecognizer *multiSelectTap;
@property (nonatomic, strong) UIButton *selectButton;

@end

@implementation GTLMessageBaseCell

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupMessageBaseCellView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupMessageBaseCellView];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Public Methods

+ (CGSize)sizeForMessageModel:(JVHGMessageModel *)model
      withCollectionViewWidth:(CGFloat)collectionViewWidth
         referenceExtraHeight:(CGFloat)extraHeight {
    return CGSizeMake(0, 0);
}

- (void)setDataModel:(JVHGMessageModel *)model {
    self.model = model;
    self.messageDirection = model.messageDirection;
    _isDisplayMessageTime = model.isDisplayMessageTime;
    if (self.isDisplayMessageTime) {
        self.messageTimeLabel.text = @"";
    }

    [self setBaseAutoLayout];
    [self updateUIForMultiSelect];
}

#pragma mark - Private Methods

- (void)setupMessageBaseCellView {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(messageCellUpdateSendingStatusEvent:)
                                                 name:@""
                                               object:nil];
    self.model = nil;
    self.baseContentView = [[UIView alloc] initWithFrame:CGRectZero];
    self.isDisplayReadStatus = NO;
    [self.contentView addSubview:_baseContentView];
}

- (void)setBaseAutoLayout {
    if (self.isDisplayMessageTime) {
        CGSize timeTextSize_ = CGSizeMake(0, 0);
        timeTextSize_ = CGSizeMake(ceilf(timeTextSize_.width + 10), ceilf(timeTextSize_.height));

        self.messageTimeLabel.hidden = NO;
        [self.messageTimeLabel setFrame:CGRectMake((self.bounds.size.width - timeTextSize_.width) / 2, 8,
                                                   timeTextSize_.width, 16)];
        [self.baseContentView setFrame:CGRectMake(0, CGRectGetMaxY(self.messageTimeLabel.frame)+12, self.bounds.size.width, self.bounds.size.height - CGRectGetMaxY(self.messageTimeLabel.frame)-12-20)];
    } else {
        if (self.messageTimeLabel) {
            self.messageTimeLabel.hidden = YES;
        }
        [self.baseContentView setFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height - (20))];
    }
}

- (void)messageCellUpdateSendingStatusEvent:(NSNotification *)notification {

}

#pragma mark - Multi select
- (void)onChangedMessageMultiSelectStatus:(NSNotification *)notification {
    [self setDataModel:self.model];
}

- (void)updateUIForMultiSelect {
//    [self.contentView removeGestureRecognizer:self.multiSelectTap];
//    if ([RCMessageSelectionUtility sharedManager].multiSelect) {
//        self.baseContentView.userInteractionEnabled = NO;
//        if (self.allowsSelection) {
//            self.selectButton.hidden = NO;
//            [self.contentView addGestureRecognizer:self.multiSelectTap];
//        } else {
//            self.selectButton.hidden = YES;
//        }
//    } else {
//        self.baseContentView.userInteractionEnabled = YES;
//        self.selectButton.hidden = YES;
//        CGRect frame = self.baseContentView.frame;
//        frame.origin.x = 0;
//        self.baseContentView.frame = frame;
//        return;
//    }
//    [self updateSelectButtonStatus];
//
//    CGRect frame = self.baseContentView.frame;
//    CGFloat selectButtonY = frame.origin.y +
//                            (RCKitConfigCenter.ui.globalMessagePortraitSize.height - SelectButtonSize.height) /
//                                2; //如果消息有头像，头像距离 baseContentView 顶部距离为 10
//    if (MessageDirection_RECEIVE == self.model.messageDirection) {
//        if (frame.origin.x < 3) { // cell不是左顶边的时候才会偏移
//            if ([RCKitUtility isRTL]) {
//                frame.origin.x = frame.origin.x - 12 - SelectButtonSpaceLeft;
//            } else {
//                frame.origin.x = SelectButtonSpaceLeft + 12;
//            }
//        }
//        self.baseContentView.frame = frame;
//    }
//    CGRect selectButtonFrame = CGRectMake(SelectButtonSpaceLeft, selectButtonY, 20, 20);
//    if ([RCKitUtility isRTL]) {
//        if (MessageDirection_RECEIVE == self.model.messageDirection) {
//            selectButtonFrame.origin.x = frame.origin.x + frame.size.width - SelectButtonSpaceLeft;
//        } else {
//            
//            selectButtonFrame.origin.x = CGRectGetMaxX(frame) - SelectButtonSpaceLeft - 20;
//        }
//    }
//    self.selectButton.frame = selectButtonFrame;
}

- (void)setAllowsSelection:(BOOL)allowsSelection {
    _allowsSelection = allowsSelection;
    if (self.model) {
        [self updateUIForMultiSelect];
    }
}

- (void)onSelectMessageEvent {
//    if ([[RCMessageSelectionUtility sharedManager] isContainMessage:self.model]) {
//        [[RCMessageSelectionUtility sharedManager] removeMessageModel:self.model];
//        [self updateSelectButtonStatus];
//    } else {
//        if ([RCMessageSelectionUtility sharedManager].selectedMessages.count >= 100) {
//            [RCAlertView showAlertController:nil message:RCLocalizedString(@"ChatTranscripts") cancelTitle:RCLocalizedString(@"OK")];
//        } else {
//            [[RCMessageSelectionUtility sharedManager] addMessageModel:self.model];
//            [self updateSelectButtonStatus];
//        }
//    }
}

- (void)updateSelectButtonStatus {
//    NSString *imgName = [[RCMessageSelectionUtility sharedManager] isContainMessage:self.model]
//                            ? @"message_cell_select"
//                            : @"message_cell_unselect";
//    UIImage *image = RCResourceImage(imgName);
//    [self.selectButton setImage:image forState:UIControlStateNormal];
}

#pragma mark - Getters and Setters

//- (UIButton *)selectButton {
//    if (!_selectButton) {
//        _selectButton = [[UIButton alloc] initWithFrame:CGRectZero];
//        [_selectButton setImage:RCResourceImage(@"message_cell_unselect") forState:UIControlStateNormal];
//        [_selectButton addTarget:self
//                          action:@selector(onSelectMessageEvent)
//                forControlEvents:UIControlEventTouchUpInside];
//        _selectButton.hidden = YES;
//        [self.contentView addSubview:_selectButton];
//        CGRect selectButtonFrame = CGRectMake(SelectButtonSpaceLeft, 0, 20, 20);
//        _selectButton.frame = selectButtonFrame;
//    }
//    return _selectButton;
//}
//
//- (UITapGestureRecognizer *)multiSelectTap {
//    if (!_multiSelectTap) {
//        _multiSelectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSelectMessageEvent)];
//        _multiSelectTap.numberOfTapsRequired = 1;
//        _multiSelectTap.numberOfTouchesRequired = 1;
//    }
//    return _multiSelectTap;
//}
//
//大量cell不显示时间，使用延时加载
- (UILabel *)messageTimeLabel {
    if (!_messageTimeLabel) {
        _messageTimeLabel = [[UILabel alloc] init];
        _messageTimeLabel.backgroundColor = [UIColor clearColor];
        _messageTimeLabel.textColor = [UIColor colorWithRed:160/255.0 green:165/255.0 blue:171/255.0 alpha:1];;
        _messageTimeLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];;
        [self.contentView addSubview:_messageTimeLabel];
    }
    return _messageTimeLabel;
}

@end


@implementation GTLMessageBaseCell (TABTools)

+ (UIImage *)tt_getDefaultMessageCellBackgroundImage:(JVHGMessageModel *)model {
    NSString *heiyou;
    if (MessageDirection_RECEIVE == model.messageDirection) {
        //: heiyou = @"bubble_right_1";
        heiyou = kTTotheString(kClimbStarfruitPolarBear);

    } else {
//        if ([self ttotheIsWhiteBubbleSendMesageCell:model.objectName]) {
//            heiyou = @"chat_to_bg_white";
//        }else{
            //: heiyou = @"bubble_left_1";
            heiyou = kTTotheString(kMacawIceApplePlunge);

//        }
    }
    UIImage *habibi = nil;
    return [self ayiguGetResizableImage:habibi];
}

+ (UIImage *)ayiguGetResizableImage:(UIImage *)cunhua {
    CGFloat w = cunhua.size.width * 0.5;
    CGFloat h = cunhua.size.height * 0.5;
    return [cunhua stretchableImageWithLeftCapWidth:w topCapHeight:h];
}

//+ (BOOL)ttotheIsWhiteBubbleSendMesageCell:(NSString *)ttothe {
//    NSArray *habibi = [GTLMessageBaseCell ttotheWhiteBubbleObjectName];
//    if ([habibi containsObject:ttothe]) return YES;
//    return NO;
//}

//+ (NSArray *)ttotheWhiteBubbleObjectName {
//    static NSArray *ttathe = nil;
//    if (!ttathe) {
//        ttathe = @[@"RC:FileMsg",@"RC:CardMsg",@"RC:LBSMsg"];
//    }
//    return ttathe;
//}


+ (CGFloat)tt_referenceExtraHeight:(Class)cellClass messageModel:(JVHGMessageModel *)model {
    CGFloat extraHeight = 20;
    if ([cellClass isSubclassOfClass:GTLMessageBaseCell.class]) {
        if (model.isDisplayMessageTime) {
            extraHeight += 8 + 16 + 12;
        }
    }
    if ([cellClass isSubclassOfClass:WQUMessageCell.class]) {
        // name label height
        if (model.isDisplayNickname && model.messageDirection == MessageDirection_RECEIVE) {
            extraHeight += 14 + 2;
        }
    }
    return extraHeight;
}

+ (CGSize)getThumbnailImageSize:(UIImage *)image {
    //图片消息最小值为 100 X 100，最大值为 240 X 240
    // 重新梳理规则，如下：
    // 1、宽高任意一边小于 100 时，如：20 X 40 ，则取最小边，按比例放大到 100 进行显示，如最大边超过240 时，居中截取 240
    // 进行显示
    // 2、宽高都小于 240 时，大于 100 时，如：120 X 140 ，则取最长边，按比例放大到 240 进行显示
    // 3、宽高任意一边大于240时，分两种情况：
    //(1）如果宽高比没有超过 2.4，等比压缩，取长边 240 进行显示。
    //(2）如果宽高比超过 2.4，等比缩放（压缩或者放大），取短边 100，长边居中截取 240 进行显示。
    CGSize imageSize = image.size;
    CGFloat maxSize = [RCCoreClient sharedCoreClient].imageCompressConfig.maxSize / 2;
    CGFloat minSize = [RCCoreClient sharedCoreClient].imageCompressConfig.minSize / 2;
    CGFloat imageMaxLength = maxSize > 0 ? maxSize : 120;
    CGFloat imageMinLength = minSize > 0 ? minSize : 50;
    if (imageSize.width == 0 || imageSize.height == 0) {
        return CGSizeMake(imageMaxLength, imageMinLength);
    }
    CGFloat imageWidth = 0;
    CGFloat imageHeight = 0;
    if (imageSize.width < imageMinLength || imageSize.height < imageMinLength) {
        return [self p_getSizeForBelowStandard:imageSize imageMinLength:imageMinLength imageMaxLength:imageMaxLength];
    } else if (imageSize.width < imageMaxLength && imageSize.height < imageMaxLength &&
               imageSize.width >= imageMinLength && imageSize.height >= imageMinLength) {
        if (imageSize.width > imageSize.height) {
            imageWidth = imageMaxLength;
            imageHeight = imageMaxLength * imageSize.height / imageSize.width;
        } else {
            imageHeight = imageMaxLength;
            imageWidth = imageMaxLength * imageSize.width / imageSize.height;
        }
    } else if (imageSize.width >= imageMaxLength || imageSize.height >= imageMaxLength) {
        return [self p_getSizeForAboveStandard:imageSize imageMinLength:imageMinLength imageMaxLength:imageMaxLength];
    }
    return CGSizeMake(imageWidth, imageHeight);
}

+ (CGSize)p_getSizeForBelowStandard:(CGSize)imageSize imageMinLength:(CGFloat)imageMinLength imageMaxLength:(CGFloat)imageMaxLength{
    CGFloat imageWidth = 0;
    CGFloat imageHeight = 0;
    if (imageSize.width < imageSize.height) {
        imageWidth = imageMinLength;
        imageHeight = imageMinLength * imageSize.height / imageSize.width;
        if (imageHeight > imageMaxLength) {
            imageHeight = imageMaxLength;
        }
    } else {
        imageHeight = imageMinLength;
        imageWidth = imageMinLength * imageSize.width / imageSize.height;
        if (imageWidth > imageMaxLength) {
            imageWidth = imageMaxLength;
        }
    }
    return CGSizeMake(imageWidth, imageHeight);
}

+ (CGSize)p_getSizeForAboveStandard:(CGSize)imageSize imageMinLength:(CGFloat)imageMinLength imageMaxLength:(CGFloat)imageMaxLength{
    CGFloat imageWidth = 0;
    CGFloat imageHeight = 0;
    if (imageSize.width > imageSize.height) {
        if (imageSize.width / imageSize.height < imageMaxLength / imageMinLength) {
            imageWidth = imageMaxLength;
            imageHeight = imageMaxLength * imageSize.height / imageSize.width;
        } else {
            imageHeight = imageMinLength;
            imageWidth = imageMinLength * imageSize.width / imageSize.height;
            if (imageWidth > imageMaxLength) {
                imageWidth = imageMaxLength;
            }
        }
    } else {
        if (imageSize.height / imageSize.width < imageMaxLength / imageMinLength) {
            imageHeight = imageMaxLength;
            imageWidth = imageMaxLength * imageSize.width / imageSize.height;
        } else {
            imageWidth = imageMinLength;
            imageHeight = imageMinLength * imageSize.height / imageSize.width;
            if (imageHeight > imageMaxLength) {
                imageHeight = imageMaxLength;
            }
        }
    }
    return CGSizeMake(imageWidth, imageHeight);
}

@end
